package com.mall507.login;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.BaseSP;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.activity.BaseUI;
import com.hzh.frame.util.MD5;
import com.hzh.frame.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

@Route(path = "/login/Testlogin")
public class TestUserLoginUI extends BaseUI implements OnClickListener{
    @Autowired
    public String targetPath;
    ImageView usernameRemove;
    ImageView passwordRemove;
    ImageView passwordDisplay;
    TextView register;
    TextView forgetPassword;
    Button login;
    EditText username;
    EditText password;
    private boolean passwordFlag=false;

    @Override
    protected void onCreateBase() {
        setContentView(R.layout.login_ui_user_login);
        getTitleView().setContent("登录");
        usernameRemove=findViewById(R.id.usernameRemove);
        passwordRemove=findViewById(R.id.passwordRemove);
        passwordDisplay=findViewById(R.id.passwordDisplay);
        register=findViewById(R.id.register);
        forgetPassword=findViewById(R.id.forgetPassword);
        login=findViewById(R.id.login);
        username=findViewById(R.id.username);
        password=findViewById(R.id.password);
        
        usernameRemove.setVisibility(View.GONE);
        passwordRemove.setVisibility(View.GONE);
        usernameRemove.setOnClickListener(this);
        passwordRemove.setOnClickListener(this);
        passwordDisplay.setOnClickListener(this);
        register.setOnClickListener(this);
        forgetPassword.setOnClickListener(this);
        login.setOnClickListener(this);
        login.setClickable(false);
        getTitleView().setRightOnclickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        username.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if(!Util.isEmpty(username.getText().toString())){
                    usernameRemove.setVisibility(View.VISIBLE);
                }else{
                    usernameRemove.setVisibility(View.GONE);
                }
                ifButton();
            }
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {}
            @Override
            public void afterTextChanged(Editable arg0) {}
        });
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if(!Util.isEmpty(password.getText().toString())){
                    passwordRemove.setVisibility(View.VISIBLE);
                }else{
                    passwordRemove.setVisibility(View.GONE);
                }
                ifButton();
            }
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {}
            @Override
            public void afterTextChanged(Editable arg0) {}
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.login:
                login();
                break;
            case R.id.usernameRemove:
                username.setText("");
                usernameRemove.setVisibility(View.GONE);
                login.setBackgroundResource(R.drawable.base_bg_eeeeee_corners_5dp_up);
                break;
            case R.id.passwordRemove:
                password.setText("");
                passwordRemove.setVisibility(View.GONE);
                login.setBackgroundResource(R.drawable.base_bg_eeeeee_corners_5dp_up);
                break;
            case R.id.passwordDisplay:
                if (passwordFlag) {
                    passwordFlag = false;
                    password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    passwordDisplay.setImageResource(R.mipmap.login_password_up);
                    password.setSelection(password.getText().length());
                } else {
                    passwordFlag = true;
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    passwordDisplay.setImageResource(R.mipmap.login_password_down);
                    password.setSelection(password.getText().length());
                }
                break;
            case R.id.register:
                ARouter.getInstance().build("/login/RegisterFirst").navigation();
                break;
            case R.id.forgetPassword:
                ARouter.getInstance().build("/login/ResetPassword").withString("common_title", "忘记密码").navigation();
                break;
        }
    }

    /**
     * 按钮是否可点击
     * */
    public void ifButton(){
        if (username.getText().toString().trim().length() >= 1 && username.getText().toString().trim().length() <=16) {
            if (password.getText().toString().trim().length() >= 6 && password.getText().toString().trim().length() <=20) {
                login.setClickable(true);
                login.setBackgroundResource(R.drawable.base_button_select);
                login.setTextColor(Color.WHITE);
            }else{
                login.setClickable(false);
                login.setBackgroundResource(R.drawable.base_bg_eeeeee_corners_5dp_up);
                login.setTextColor(Color.parseColor("#8a8a8a"));
            }
        }else{
            login.setClickable(false);
            login.setBackgroundResource(R.drawable.base_bg_eeeeee_corners_5dp_up);
            login.setTextColor(Color.parseColor("#8a8a8a"));
        }
    }
	
	/**
	 * 登录
	 * */
	public void login(){
		JSONObject params = new JSONObject();
		if (username.getText().length() == 0) {
			alert("请输入手机号/帐号！");
		} else if (password.getText().length() == 0) {
			alert("请输入密码！");
		}else if (password.getText().length() < 6) {
			alert("密码少于6位！");
		} else {
			try {
				params.put("userName", username.getText().toString());
				params.put("password", MD5.md5(password.getText().toString()));
				params.put("DEVICE", "暂无");
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
            BaseHttp.getInstance().query(3028, params, new HttpCallBack() {
				@Override
				public void onSuccess(JSONObject response) {
						if("1".equals(response.optString("result"))){
							if("1".equals(response.optJSONObject("data").optString("code"))){
								User user =new User();
								JSONObject js = response.optJSONObject("data").optJSONObject("data");
                                user.setPhone(js.optString("PHONE"));
                                user.setPassword(js.optString("password"));
                                user.setHead(js.optString("photoUrl"));
                                user.setUsername(js.optString("userName"));
                                user.setUserid(js.optString("id"));
                                user.setAlipayAcount(js.optString("alipay"));
                                user.setAlipayName(js.optString("alipayName"));
                                user.setVip(js.optBoolean("VIP"));
                                user.setAder(js.optBoolean("ADER"));
                                user.setRealname(js.optBoolean("trueName"));
                                user.setNewtask(js.optBoolean("NEWTASK"));
                                user.setInviter(js.optString("INVITER"));
                                user.setService(js.optString("service_user"));
                                user.setSvip(js.optInt("SVIP"));
                                user.setSvipShow(js.optBoolean("svipShow") ? 1 : 0);
                                user.setSvipMoney(js.optString("svipMoney"));
                                user.setBankAccount(js.optString("back_card"));
                                user.setBankAddress(js.optString("opening_bank_address"));
                                user.setBankMasterName(js.optString("back_card_name"));
                                user.setBankName(js.optString("opening_bank"));
                                user.setUserLevel(js.optInt("level"));
                                user.setCorporate(js.optDouble("corporate"));
                                if(js.optBoolean("regional",false)){
                                    user.setRegional(1);
                                }else{
                                    user.setRegional(0);
                                }
                                user.save();
								//用户登录成功
								Intent iu = new Intent("com.gangs.adbao.activity.CLIENTMAINCHANGEBR");
								iu.putExtra("pageName", "user");
								iu.putExtra("flag", 1);
								sendBroadcast(iu);
								
								loginJPush(user.getUserid());
                                BaseSP.getInstance().put("login",true);
                                if(!Util.isEmpty(targetPath)){
                                    ARouter.getInstance().build(targetPath).navigation();
                                }else{
                                    alert("登录成功");
                                }
							}else{
								alert(response.optJSONObject("data").optString("msg"));
							}
						}else{
							alert("登录失败");
						}
				}
            });
		}
	}
	
	/**
	 * 登录极光推送
	 * @param userid 用户id
	 * */
    public void loginJPush(String userid){
        if(!"null".equals(BaseSP.getInstance().getString("JPushRegistrationId", "null"))){
            JSONObject params=new JSONObject();
            try {
                params.put("userid", userid);
                params.put("registrationId", BaseSP.getInstance().getString("JPushRegistrationId", "null"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
//            BaseHttp.getInstance().write(null,2972, params, new HttpCallBack(){
//                @Override
//                public void onSuccess(JSONObject response) {
//
//                }
//                @Override
//                public void onFail(){
//                }
//            });
        }
    }
}
